<template>
  <div>
    <el-form
      ref="elFormRef"
      label-width="auto"
      label-position="top"
      :rules="rules"
      :model="formData"
    >
      <el-form-item prop="name" label="节点名称">
        <el-input
          v-model="formData.name"
          placeholder="请填写节点名称"
        />
      </el-form-item>

      <el-form-item prop="type" label="审批方式">
        <el-radio-group v-model="formData.type">
          <el-radio
            label="countersign"
            style="margin-bottom: 10px;"
          >
            会签（需所有人同意）
          </el-radio>
          <el-radio label="orsign">或签（其中一人同意即可）</el-radio>
        </el-radio-group>
      </el-form-item>
      <div
        v-for="(item, index) in formData.assignees"
        :key="index"
      >
        <el-form-item prop="assignees">
          <div class="approver">
            <div class="approver__header">
              <div>{{ `审批人${index + 1}` }}</div>
              <div @click="handleRemoveApprover(index)">
                <i class="el-icon-delete" />
              </div>
            </div>
            <div class="approver__body">
              <el-radio-group
                v-model="formData.assignees[index].assignee_type"
                @input="handleAssigneeTypeChange($event, index)"
              >
                <el-radio label="user">指定人员</el-radio>
                <el-radio label="role">指定角色</el-radio>
              </el-radio-group>
              <el-divider />
              <div class="title">
                {{ formData.assignees[index].assignee_type === 'user' ? '选择指定人员' : '选择角色' }}
              </div>
              <div v-if="formData.assignees[index].assignee_type === 'user'" class="add-btn">
                <div class="add-btn__btn" @click="handleOpenUserSelect(index)">
                  <i v-if="!formData.assignees[index].assignee_id" class="el-icon-plus" />
                  <span v-else>{{ formData.assignees[index].assignee_name }}</span>
                </div>
              </div>

              <div v-if="formData.assignees[index].assignee_type === 'role'">
                <el-select
                  v-model="formData.assignees[index].assignee_id"
                  placeholder="请选择"
                  size="mini"
                  style="margin-top: 10px;"
                  @change="($event) => handleSelectChange($event, index)"
                >
                  <el-option
                    v-for="role in rolesListFormat"
                    :key="role.value"
                    :label="role.label"
                    :value="role.value"
                  />
                </el-select>
              </div>
            </div>
          </div>
        </el-form-item>
      </div>

      <el-form-item>
        <el-button
          type="text"
          icon="el-icon-plus"
          @click="handleAddApprover"
        >
          添加审批人
        </el-button>
      </el-form-item>
    </el-form>

    <SelectList
      v-model="isSelected"
      :visible.sync="showUserSelect"
      :total="total"
      :loading="loading"
      :list="userListFormat"
      title="选择审批人"
      @onConfirm="handleConfirm"
      @onPageChange="handlePageChange"
      @onSearch="handleSearch"
    />
  </div>
</template>
<script>
import SelectList from '@/components/SelectList/SelectList.vue'
import { getAllUser } from '@/api/v2/personnel'
import { getRoles } from '@/api/role'
export default {
  name: '',
  components: {
    SelectList
  },
  props: {
    formData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      rules: {
        name: [{ required: true, message: '节点名称不能为空', trigger: ['change', 'blur'] }]
      },
      approvalMethod: [
        { label: '会签（需所有人同意）', value: 'countersign' },
        { label: '或签（其中一人同意或拒绝即可）', value: 'orsign' }
      ],
      approver: 'user',
      showUserSelect: false,
      userList: [],
      roles: [],
      total: 0,
      loading: false,
      isSelected: [],
      currentIndex: null,
      assigneeType: 'user',
      assignees: []
    }
  },
  computed: {
    userListFormat() {
      return this.userList.map(item => {
        return {
          label: item.username,
          value: item.id
        }
      })
    },

    rolesListFormat() {
      return this.roles.map(item => {
        return {
          label: item.label_name,
          value: item.id
        }
      })
    }
  },
  created() {
    this.getRoles()
  },
  methods: {
    handleAddApprover() {
      this.formData.assignees.push({
        assignee_type: 'user',
        assignee_id: null
      })
    },

    handleRemoveApprover(index) {
      this.formData.assignees.splice(index, 1)
    },

    async getRoles() {
      const res = await getRoles()
      this.roles = res.data
    },

    async getUsers(params) {
      this.loading = true
      try {
        const res = await getAllUser(params)
        this.userList = res.data
        this.total = res.meta.total
      } catch (e) {
        throw new Error(e?.response?.data?.message || '用户列表获取失败')
      } finally {
        this.loading = false
      }
    },

    handleOpenUserSelect(index) {
      this.currentIndex = index
      const current = this.formData.assignees[index].assignee_id
      this.isSelected = [current]
      this.getUsers()
      this.showUserSelect = true
    },

    handlePageChange(page, username) {
      this.getUsers({ page, username })
    },

    handleSearch({ page, keyword }) {
      this.getUsers({ page, username: keyword })
    },

    handleConfirm(e, val) {
      for (const assignee of this.formData.assignees) {
        if (assignee.assignee_id === e) {
          this.$notify.error({
            title: '错误',
            message: '该审批人已存在！'
          })
          return
        }
      }

      this.formData.assignees[this.currentIndex].assignee_id = e
      this.formData.assignees[this.currentIndex].assignee_name = val.label
    },

    handleAssigneeTypeChange(e, index) {
      this.formData.assignees[index].assignee_id = null
      this.formData.assignees[index].assignee_name = ''
    },
    async validate() {
      const formRes = await this.validateForm()
      const assigneesRes = this.validateAssignees()

      console.log('formRes, assigneesRes --------->', formRes, assigneesRes)

      if (!formRes || !assigneesRes) return false

      return true
    },

    validateAssignees() {
      let error = 0
      for (const i of this.formData.assignees) {
        if (!i.assignee_id) {
          error += 1
        }
      }

      if (error > 0) {
        this.$notify.error({
          title: '错误',
          message: '请将审批人信息补充完整！'
        })
        return false
      }

      return true
    },

    validateForm() {
      return new Promise(resolve => {
        this.$refs.elFormRef.validate(flag => {
          if (!flag) {
            this.$notify.error({
              title: '错误',
              message: '请将信息补充完整！'
            })
            resolve(false)
          }

          resolve(true)
        })
      })
    },

    handleSelectChange(e, index) {
      console.log('index --------->', index)
      console.log('e --------->', e)
      let count = 0
      for (const assignee of this.formData.assignees) {
        if (assignee.assignee_type === 'role' && assignee.assignee_id === e) {
          count++
        }
      }

      if (count >= 2) {
        this.$notify.error({
          title: '错误',
          message: '该审批角色已存在！'
        })
        this.formData.assignees[index].assignee_id = null
        return
      } else {
        this.formData.assignees[index].assignee_name =
          this.rolesListFormat.find(item => item.value === e).label
      }
    }

  }
}
</script>
<style lang="scss" scoped>
.approver {
  width: 100%;
  border-radius: 10px;
  overflow: hidden;
  border: 1px solid #DCDFE6;
  &__header {
    padding: 0 10px;
    background-color: #DCDFE6;
    display: flex;
    justify-content: space-between;
  }

  &__body {
    line-height: normal;
    padding: 10px;

    .title {
      font-size: 14px;
      line-height: normal;
      font-weight: bold;
    }

    .add-btn {
      margin-top: 10px;
      display: flex;

      &__btn {
        cursor: pointer;
        padding: 10px;
        background-color: #F5F5F5;
      }
    }
  }

  .el-divider--horizontal {
    margin: 10px 0;
  }
}

::v-deep .el-radio__original {
  display: none !important; /* 隐藏原生 radio 输入，但仍然允许交互 */
}

::v-deep .el-radio:focus:not(.is-focus):not(:active):not(.is-disabled) .el-radio__inner {
  box-shadow: none !important;
}
</style>
